var game = {
  init: function () {
    this.sceneData = [];            // 场景数据
    this.lotteryRewardList = [];    // 奖品列表
    this.activeElement = null;      // 当前编辑元素
    this.activeIndex = null;        // 当前奖品index
    this.formData = {};             // 全局提交参数
    this.id = null;                 // 编辑状态 当前游戏模板ID
    this.eventBinding();            // 事件绑定合集
    this.render();                  // 入口
  },

  getSceneData: function () {

    var _this = this;
    this.request({
      url: '/public/scene/get',
      type: 'get',
      dataType: 'json',
      success: function (data) {

        if (data.msg) {
          alert('接口[/public/scene/get]报错：' + data.msg)
          return ;
        }

        var data = JSON.parse(data);
        if (data.success) {
          _this.sceneData = data.data
          _this.initScene()
        }

      }
    })
  },

  // 事件绑定
  eventBinding: function () {
    var _this = this;

    $(document)
      .on('change', '.J-gameType', function () { // 切换游戏类型，获取游戏demo
        _this.request({
          url: '/lottery/getLotteryDemo?bizType=' + $(this).val(),
          type: 'get',
          success: function (data) {

            if (data.msg) {
              alert('接口[/lottery/getLotteryDemo]报错：' + data.msg)
              return ;
            }

            var data = JSON.parse(data);
            if (data.success) {
              $('.example').html(data.data.demo)
              _this.initMaterialConfig()
            }
          },
          error: function (data) {
            alert(data.msg)
          }
        })

      }).on('click', '#J_createPrize', function () { // 创建奖品

        if (_this.lotteryRewardList.length >= $('[data-type=PRIZEITEM]').length) {
          alert('已经达到奖品配置数量上限！')
          return ;
        }

        _this.setModalPrize('create', null)

      }).on('click', '.J_editPrize', function () { // 编辑奖品

        _this.setModalPrize('edit', this)

      }).on('click', '.J_delPrize', function () { // 删除奖品

        var index = $('#J_prizeList').find($(this).closest('tr')).index();
        _this.lotteryRewardList.splice(index, 1)
        _this.rednerRewardList();

      }).on('click', '#J_prizeConfirm', function () { // 弹窗 保存 & 修改按钮
        if(!_this.checkcreateInfo()) {
          alert('请填写完整');
          return;
        }
        _this.setPrizeData($(this).attr('data-action'))

      }).on('change', 'input.imageUp', function () { // 上传奖品图片

        $(this).attr('id', 'imagefile')
        _this.ajaxImageUpload('imagefile', function (url) {
          var addImgDiv = $('.addImgDiv');
          addImgDiv.find("img").attr("src", url)
          addImgDiv.find("input[type='hidden']").val(url)
          addImgDiv.find("input[name='file']").attr('id', '')
          $('.imageUp').replaceWith('<input type="file" name="file" class="imageUp" id="" />')
        })

      }).on('change', 'input.bannerUrl', function () { // 上传奖品图片

        $(this).attr('id', 'bannerUrl')
        _this.ajaxImageUpload('bannerUrl', function (url) {
          var addImgDiv = $('.addBannerUrlDiv');
          addImgDiv.find("img").attr("src", url)
          addImgDiv.find("[name=bannerUrl]").val(url)
          addImgDiv.find("input[name='file']").attr('id', '')
          $('.bannerUrl').replaceWith('<input type="file" name="file" class="bannerUrl" id="" />')
        })

      }).on('click', '.J-configWrap > li', function () { // 可编辑元素切换

        var $this = $(this);
        if (!$this.hasClass('active')) {
          $this
          .addClass('active')
          .siblings().removeClass('active')

          _this.changeEditOption($this)
        }

      }).on('change', '.J-gameUploadBtn', function () { // 修改图片素材类型 src, background-image

        var gameUploadBtn = $('.J-gameUploadBtn');
        gameUploadBtn.attr('id', 'J-gameUploadBtn')

        _this.ajaxImageUpload('J-gameUploadBtn', function (url) {

          var id = $(_this.activeElement).attr('data-class'),
              type = $(_this.activeElement).attr('data-type');

          gameUploadBtn.attr('id', '')

          if (type === 'IMG') {
            $('[data-id=' + id +']').attr('src', url)
          }

          if (type === 'BACKGROUNDIMG') {
            $('[data-id=' + id +']')
              .css('background-image', 'url("'+ url +'")')
              .attr('data-src', url)
          }

          console.log(_this.formData);

          $.extend(true, _this.formData, {
            "sceneConfig" : {
              [id]: url
            }
          })

          console.log(_this.formData);



          $(_this.activeElement).find('img').attr('src', url)
          $('.J-previewImgUpload').attr('src', url)
          $('.J-gameUploadBtn').replaceWith('<input type="file" name="file" class="game-upload-btn J-gameUploadBtn" id=""/>')
        })

      }).on('click', '.J-next', function () { // 下一步

        var prizeItem = $('[data-type=PRIZEITEM]');
        // 判断是游戏类型数据
        if(_this.checkBaseInfo()) {
          alert('请填写游戏的基本信息');
          return;
        }
        if (_this.lotteryRewardList.length < prizeItem.length) {
          alert('需要配置' + prizeItem.length + '个奖品' )
          return;
        }

        prizeItem.map(function (index, item) {
          $(item).find('[data-role="PRIZENAME"]').html(_this.lotteryRewardList[index].title)
          $(item).find('[data-type="PRIZEIMG"]').attr('src', _this.lotteryRewardList[index].iconUrl)
        })

        $('.J-gameInfo').hide()
        $('.J-gameConfig').show()

      }).on('click', '.J-submit', function () { // 表单提交

        var data = $.extend(
          true,
          _this.formData,
          {
            type: $('.J-gameType').val(),
            title: $('.J-gameTitle').val(),
            perDayLimit: $('.J-perDayLimit').val(),
            remark: $('.J-remark').val(),
            bannerUrl: $('[name=bannerUrl]').val(),
            lotteryRewardList: _this.lotteryRewardList,
            sceneHtml: $('.example').html(),
            sceneConfig: (typeof _this.formData.sceneConfig === 'string') ? _this.formData.sceneConfig : JSON.stringify(_this.formData.sceneConfig),
            sceneCode: _this.formatScene()
          }
        );

        if (_this.id) { // edit
          data.id = _this.id;
          _this.request({
            url: '/lottery/update.action',
            type: 'post',
            data: JSON.stringify(data),
            dataType: 'json',
            success: function (data) {
              if (data.msg) {
                alert('接口[/lottery/update.action]报错：' + data.msg)
                return ;
              }
              var data = JSON.parse(data);
              if (data.success) {
                alert('修改成功！')
                location.replace("/lottery/lotteryList.htm#lotteryManager")
              }
            }
          })
          return ;
        }

        _this.request({ // create
          url: '/lottery/create.action',
          type: 'post',
          data: JSON.stringify(data),
          dataType: 'json',
          success: function (data) {

            if (data.msg) {
              alert('接口[/lottery/create.action]报错：' + data.msg)
              return ;
            }

            var data = JSON.parse(data);
            if (data.success) {
              alert('提交成功！')
              location.replace("/lottery/lotteryList.htm#lotteryManager")
            }

          }
        })

      }).on('click', '.J-return', function () { // 返回按钮

        $('.J-gameConfig').hide()
        $('.J-gameInfo').show()

      })

  },

  //场景值
  formatScene: function () {

    var arr = [],
        sceneVal = $("#J_scene").select2("data");
    sceneVal.map(function (item, index) {
      arr.push(Number(item.id))
    })

    return arr;

  },
  checkBaseInfo: function () {
  var gameTitle = $('.J-gameTitle').val(),
      gameLimitNum = $('.J-perDayLimit').val(),
      gameRemark = $('.J-remark').val();
  if(gameTitle === '' || gameLimitNum === '' || gameRemark === '')  {
    return true;
  }else {
    return false;
  }
},
  checkcreateInfo: function() {
      var formList = $('#J_prizeBody>.form-horizontal>.form-group');
      for(var i=0; i< formList.length; i++) {
        if($(formList[i]).attr('style')) {
        }else {
          var listchildren = $(formList[i]).find('.col-sm-8').children();
          if($(listchildren).attr('class') === 'form-control') {
              console.log($(listchildren).attr('id'))
              if($(listchildren).val() === '' && $(listchildren).attr('id') != 'J_md_num') {
                return false;
              }
          }else if($(listchildren).attr('class') === "addImgDiv"){
            console.log($(listchildren).find('[name=iconUrl]').val())
            if($(listchildren).find('[name=iconUrl]').val() === '') {
              return false;
            }
          }

        }


      }
      return true;
    },
  // 初始化场景
  initScene: function () {

    var arr = [],
        data = this.sceneData;
    data && data.length && data.map(function (item, index) {
      arr.push({
        "id": item.code,
        "text": item.name
      })
    })

    $('#J_scene').select2({
      data:  arr
    })

  },

  // render
  render: function () {
    this.getSceneData();            // 场景数据
    var id = common.getQueryString(location.href, 'id');
    if (id) {
      this.id = id;
      this.getFormData(id);
      return ;
    }
    $('.J-gameType').trigger('change')

  },

  // 初始化素材配置
  initMaterialConfig: function () {

    var _this = this,
        htmlStr = '',
        $example = $('.example'),
        configWrap = $('.J-configWrap'),
        $img = $example.find('[data-type="IMG"]'), // <img src="" />
        $text = $example.find('[data-type="TEXT"]'), // 文案
        $border = $example.find('[data-type="BORDER"]'), // 文案
        $backgroundColor = $example.find('[data-type="BACKGROUNDCOLOR"]'), // 背景色
        $backgroundImg = $example.find('[data-type="BACKGROUNDIMG"]'), // 背景图片
        createDom = function (data) {
          data && data.length && data.map(function (index, item) {

            var type = $(item).attr('data-type'),
                size = $(item).attr('data-size'),
                id = $(item).attr('data-id');

            if (type === 'IMG') {

              htmlStr += '<li data-size="' + size + '" data-class="' + id + '" data-type="IMG">' +
                            '<div><img src="' + $(item).attr('src') + '"/></div>' +
                            '<span>' + $(item).attr('data-title') + '</span>' +
                          '</li>'

            $.extend(true, _this.formData, {"sceneConfig": {[id]: $(item).attr('src')}})

            } else if (type === 'BACKGROUNDIMG') {

              htmlStr += '<li data-size="' + size + '" data-class="' + id + '" data-type="BACKGROUNDIMG">' +
                            '<div><img src="' + $(item).attr('data-src') + '"/></div>' +
                            '<span>' + $(item).attr('data-title') + '</span>' +
                          '</li>'

            $.extend(true, _this.formData, {"sceneConfig": {[id]: $(item).attr('data-src')}})

            } else if (type === 'BACKGROUNDCOLOR') {

              htmlStr += '<li data-class="'+ id +'" data-type="BACKGROUNDCOLOR">' +
                            '<div style="background-color: ' + $(item).css('backgroundColor') + '"></div>' +
                            '<span>' + $(item).attr('data-title') + '</span>' +
                          '</li>'

            $.extend(true, _this.formData, {"sceneConfig": {[id]: $(item).css('backgroundColor')}})

            } else if (type === 'TEXT') {

              htmlStr += '<li data-class="' + id + '" data-type="TEXT">' +
                            '<div style="background-color: ' + $(item).css('color') + '"></div>' +
                            '<span>' + $(item).attr('data-title') + '</span>' +
                          '</li>'

            $.extend(true, _this.formData, {"sceneConfig": {[id]: $(item).css('color')}})

            } else if (type === "BORDER") {

              htmlStr += '<li data-class="' + id + '" data-type="BORDER">' +
                            '<div style="background-color: ' + $(item).css('borderColor') + '"></div>' +
                            '<span>' + $(item).attr('data-title') + '</span>' +
                          '</li>'

              $.extend(true, _this.formData, {"sceneConfig": {[id]: $(item).css('borderColor')}})

            } else {}

          })
        };

    // colpick初始化
    $('#colper').colpick({
      flat: true,
      colorScheme: 'light',
      submitText: '确定',
      onSubmit: function (hsb, hex, rgb, el) {
        $(el).css('background-color', '#' + hex)
        _this.setMaterialColor(hex)
      }
    })

    createDom($img)
    createDom($text)
    createDom($backgroundColor)
    createDom($backgroundImg)
    createDom($border)
    configWrap.html(htmlStr)

  },

  // 获取回填数据
  getFormData: function (id) {

    var _this = this;
    this.request({
      url: '/lottery/getLottery?id=' + id,
      type: 'get',
      dataType: 'json',
      success: function (data) {

        if (data.msg) {
          alert('接口[/lottery/getLottery]报错：' + data.msg)
          return ;
        }

        var data = JSON.parse(data);
        if (data.success) {
          _this.renderForm(data.data)
        }

      }
    })
  },

  // 回显
  renderForm: function (data) {

    var lotteryDO = data.lotteryDO,
        lotteryRewardDOs = data.lotteryRewardDOs,
        sceneCode = lotteryDO.sceneCode && lotteryDO.sceneCode.replace('[', '').replace(']', '');

    $('.J-remark').val(lotteryDO.remark)
    $('.J-gameTitle').val(lotteryDO.title)
    $('.example').html(lotteryDO.sceneHtml)
    $('#J_bannerUrl').attr('src', lotteryDO.bannerUrl)
    $('.J-perDayLimit').val(lotteryDO.perDayLimit)
    $('.J-gameType')
      .attr("disabled", true)
      .find('option[value='+ lotteryDO.type +']').attr('selected', true)

    $("#J_scene").val(sceneCode && sceneCode.split(',')).trigger('change')

    $.extend(true, this.formData, {"sceneConfig": JSON.parse(lotteryDO.sceneConfig)})

    this.lotteryRewardList = data.lotteryRewardDOs
    this.rednerRewardList()
    this.initMaterialConfig()

  },

  // 根据不同编辑类型展示操作区
  changeEditOption: function (e) {

    this.activeElement = e;
    var previewImgUpload = $('.J-previewImgUpload'),
        imgSrc = $(e).find('img').attr('src'),
        colorPicker = $('.J-colorPicker'),
        type = $(e).attr('data-type'),
        imgUpload = $('.J-imgUpload');

    $('#J_size').html('')
    imgUpload.hide();
    colorPicker.hide();

    if (type === 'IMG' || type === 'BACKGROUNDIMG') {

      imgUpload.show()
      previewImgUpload.attr('src', imgSrc)


      if ($(e).attr('data-size') !== 'undefined') {
        $('#J_size').html('尺寸：' + $(e).attr('data-size') + 'px')
      }

    }

    if (type === 'BACKGROUNDCOLOR' || type === 'TEXT' || type === 'BORDER') {

      colorPicker.show()

    }

  },

  // 颜色编辑
  setMaterialColor: function (hex) {

    var obj = $(this.activeElement),
        dataClass = obj.attr('data-class'),
        dataType = obj.attr('data-type');
    obj.children('div').css('background-color', '#'+hex);

    if (dataType === 'TEXT') {

      $('[data-id=' + dataClass + ']').css('color', '#' + hex)

    }

    if (dataType === 'BORDER') {

      $('[data-id=' + dataClass + ']').css({'border-color': '#' + hex, 'box-shadow': '0 0 5px #' + hex})

    }

    if (dataType === 'BACKGROUNDCOLOR') {

      $('[data-id=' + dataClass + ']').css('background-color', '#' + hex)

    }

    console.log(this.formData)

    $.extend(true, this.formData, {
      "sceneConfig": {
        [dataClass]: '#' + hex
      }
    })

    console.log(this.formData);

  },

  // 奖品编辑弹窗数据回显
  setModalPrize: function (type, ele) {

    var $tr = $(ele).closest('tr');
    $('#backImg').attr('src', '')
    $('#J_prizeBody > form input').val('')
    $('#J_md_num').val($tr.find('.J_td_num').html())
    $('#J_md_rate').val($tr.find('.J_td_rate').html())
    $('#J_md_title').val($tr.find('.J_td_title').html())
    $('#J_md_weight').val($tr.find('.J_td_weight').html())
    $('[name=iconUrl]').val($tr.find('.J_td_iconUrl').attr('src'))
    $('#backImg').attr('src', $tr.find('.J_td_iconUrl').attr('src'))
    $('.J_prizeSize').html('[' + $('.J_prizeSize').val() + ']')

    $('#J_prizeTitle')
      .html(type === 'create' ? '创建奖品' : '编辑奖品')

    $('#J_prizeConfirm')
      .html(type === 'create' ? '保存' : '确认修改')
      .attr('data-action', type === 'create' ? 'create' : 'edit')

    $('#J_prizeModal').modal('show')

    this.activeIndex = $('#J_prizeList').find($tr).index()

  },

  // 奖品编辑列表操作
  setPrizeData: function (action) {

    var _this = this,
        scene = [],
        data= {'iconUrl': $('[name=iconUrl]').val()};
    $('#J_prizeBody > form input:visible, #J_prizeBody > form select').not('[type=file]').each(function (index, item) {
      var key = $(item).attr('name'),
        value = $(item).val();
      data[key] = value
      if (_this.id) {
        data.lotteryId = _this.id
      }
    })

    var create = function (data) {
      _this.lotteryRewardList.push(data)
    }

    var edit = function (data) {
      _this.lotteryRewardList.map(function (item, index) {
        if (_this.activeIndex === index) {
          $.extend(_this.lotteryRewardList[index], data)
        }
      })
    }

    action === 'create' ? create(data) : edit(data)
    this.rednerRewardList()

  },

  // 奖品列表
  rednerRewardList: function () {

    var htmlStr = '',
        list = this.lotteryRewardList,
        prizeList = $('#J_prizeList'),
        prizeModal = $('#J_prizeModal');

    list.map(function(item, index) {

      var id = item.id || item.id === 0 ? item.id : '',
          iconUrl = item.iconUrl ? item.iconUrl : '',
          title = item.title ? item.title : '',
          num = item.num || item.num === 0 ? item.num : '',
          rate = item.rate || item.rate === 0 ? item.rate : '',
          weight = item.weight || item.weight === 0 ? item.weight : '';
      htmlStr += '<tr>' +
                    '<td class="J_td_id">' + id + '</td>' +
                    '<td><img class="preview-img J_td_iconUrl" src="' + iconUrl + '" /></td>' +
                    '<td class="J_td_title">' + title + '</td>' +
                    '<td>广告优惠券</td>' +
                    '<td class="J_td_num">' + num + '</td>' +
                    '<td class="J_td_rate">' + rate +'</td>' +
                    '<td class="J_td_weight">' + weight + '</td>' +
                    '<td>' +
                      '<a href="javascript:void(0);" class="J_editPrize">编辑</a>' +
                    '</td>' +
                  '</tr>'
    })

    prizeList.html(htmlStr)
    prizeModal.modal('hide')

  },

  // 图片上传
  ajaxImageUpload: function (fileElementId, callback) {

    $.ajaxFileUpload({
      url: '/fileUpload/ajaxImageUpload.action',
      secureuri: false,
      fileElementId: fileElementId,
      dataType: 'json',
      success: function (data, status) {
        if (data.success) {
          var url = data.data.url + data.data.bucketName
          console.log('upload success:' + url)
          callback(url)
        }
      },
      error: function (error) {
        console.log(error)
      }
    })

  },

  // ajax
  request: function (config) {

    var params = $.extend({
      dataType: 'json',
      headers: {
        'Content-Type':'text/plain;charset=UTF-8'
      },
      error: function (error) {
        if (error.statusText) {
          alert(error.statusText)
        }
      }
    }, config)
    $.ajax(params)

  },

}

// 调用
game.init()
